//
//  LKPickerViewController.m
//  LKPickerViewDemo
//
//  Created by LIUKUN-PC on 16/6/14.
//  Copyright © 2016年 liukun. All rights reserved.
//

#import "LKPickerViewController.h"
#import "ZXContentAutoFit.h"

#define SCREEN_WIDTH [[UIScreen mainScreen] bounds].size.width
#define SCREEN_HEIGHT [[UIScreen mainScreen] bounds].size.height

@interface LKPickerViewController ()<UIPickerViewDataSource, UIPickerViewDelegate>

@property (nonatomic, copy) void(^datePickCompletionBlock)(NSDate *selectedDate);
@property (nonatomic, copy) void(^customPickCompletionBlock)(NSInteger selectedIndex);

@property (nonatomic, strong) NSArray<NSString *> *dataArray;
@property (nonatomic, strong) NSDate *selectedDate;
@property (nonatomic, assign) NSInteger selectedIndex;

@property (nonatomic, assign) LKPickerType pickerType;
@property (nonatomic, strong) UIDatePicker *datePicker;
@property (nonatomic, strong) UIPickerView *pickerView;

@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UIButton *doneButton;
@property (nonatomic, strong) UIButton *cancelButton;
@property (nonatomic, strong) UILabel *currentValueLabel;

@end

@implementation LKPickerViewController

#pragma mark - API

+ (instancetype)datePickerVCWithSelectedDate:(NSDate *)selectedDate completion:(void (^)(NSDate *))completion {
    LKPickerViewController *pickerVC = [[LKPickerViewController alloc] init];
    pickerVC.datePickCompletionBlock = completion;
    pickerVC.selectedDate = selectedDate;
    pickerVC.pickerType = LKPickerTypeDate;
    return pickerVC;
}

+ (instancetype)customPickerVCWithDataSource:(NSArray<NSString *> *)dataArray selectedIndex:(NSInteger)selectedIndex completion:(void (^)(NSInteger))completion {
    LKPickerViewController *pickerVC = [[LKPickerViewController alloc] init];
    pickerVC.dataArray = dataArray;
    pickerVC.customPickCompletionBlock = completion;
    pickerVC.selectedIndex = selectedIndex;
    pickerVC.pickerType = LKPickerTypeCustom;
    return pickerVC;
}

#pragma mark - inits

- (instancetype)init {
    if (self = [super init]) {
        [self initData];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        [self initData];
    }
    return self;
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        [self initData];
    }
    return self;
}

- (void)initData {
    self.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    self.pickerViewFontSize = 17;
    self.pickerViewRowHeight = 44;
}


#pragma mark - View Life Cycle

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor clearColor];
    CGRect bounds = self.view.bounds;
    bounds.origin.y -= 240;
    self.view.bounds = bounds;
    
    [self.view addSubview:self.headerView];
    [self.headerView addSubview:self.cancelButton];
    [self.headerView addSubview:self.doneButton];
    [self.headerView addSubview:self.currentValueLabel];
    
    if (self.pickerType == LKPickerTypeDate) {
        [self.headerView addSubview:self.datePicker];
        self.datePicker.date = self.selectedDate;
    } else {
        [self.headerView addSubview:self.pickerView];
        [self.pickerView selectRow:self.selectedIndex inComponent:0 animated:NO];
    }
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [UIView animateWithDuration:0.4 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        self.view.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.3];
        CGRect bounds = self.view.bounds;
        bounds.origin.y = 0;
        self.view.bounds = bounds;
        
        if (self.showBlock) {
            self.showBlock();
        }
        
    } completion:nil];
}


#pragma mark - Action

- (void)finishPick:(UIButton *)sender {
    [UIView animateWithDuration:0.4 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        self.view.backgroundColor = [UIColor clearColor];
        CGRect bounds = self.view.bounds;
        bounds.origin.y -= 240;
        self.view.bounds = bounds;
        
        if (self.dismissBlock) {
            self.dismissBlock(YES);
        }
        
    } completion:^(BOOL finished) {
        __weak typeof(self) weakSelf = self;
        [self dismissViewControllerAnimated:NO completion:^{
            if (weakSelf.datePickCompletionBlock && weakSelf.pickerType == LKPickerTypeDate) {
                weakSelf.datePickCompletionBlock(weakSelf.selectedDate);
                
            } else if (weakSelf.customPickCompletionBlock && weakSelf.pickerType == LKPickerTypeCustom) {
                weakSelf.customPickCompletionBlock(weakSelf.selectedIndex);
            }
        }];
    }];

    
    
}

- (void)cancelPick:(UIButton *)sender {
    [self dismiss];
}

- (void)datePickerValueChanged:(UIDatePicker *)sender {
    
    self.selectedDate = sender.date;
}

- (void)dismiss {
    [UIView animateWithDuration:0.4 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        self.view.backgroundColor = [UIColor clearColor];
        CGRect bounds = self.view.bounds;
        bounds.origin.y -= 240;
        self.view.bounds = bounds;
        
        if (self.dismissBlock) {
            self.dismissBlock(NO);
        }
        
    } completion:^(BOOL finished) {
        [self dismissViewControllerAnimated:NO completion:nil];
    }];
}

#pragma mark - Picker View Data Source & Delegate

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    return  self.dataArray.count;
}

//- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
//    return self.dataArray[row];
//}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    UILabel* label = (UILabel*)view;
    if (!label){
        label = [[UILabel alloc] init];
        label.numberOfLines = 2;
        label.textAlignment = NSTextAlignmentCenter;
        label.font = [UIFont systemFontOfSize:self.pickerViewFontSize];
    }
    label.text = self.dataArray[row];

    return label;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    self.selectedIndex = row;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component {
    return self.pickerViewRowHeight;
}



#pragma mark - Getter(LazyLoad) & Setter

- (UIPickerView *)pickerView {
    if (_pickerView) {
        return _pickerView;
    }
    _pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 40, SCREEN_WIDTH, 200)];
    _pickerView.delegate = self;
    _pickerView.dataSource = self;
    
    _pickerView.backgroundColor = [UIColor whiteColor];
    
    return _pickerView;
}

- (UIDatePicker *)datePicker {
    if (_datePicker) {
        return _datePicker;
    }
    _datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 40, SCREEN_WIDTH, 200)];
    //模式，日期或时间
    _datePicker.datePickerMode = UIDatePickerModeDateAndTime;
    
    //最小间隔5分钟
    _datePicker.minuteInterval = 5;
    [_datePicker addTarget:self action:@selector(datePickerValueChanged:) forControlEvents:UIControlEventValueChanged];
    _datePicker.backgroundColor = [UIColor whiteColor];
    
    
    
    
    return _datePicker;
}

- (UIView *)headerView {
    if (_headerView) {
        return _headerView;
    }
    _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - 240, SCREEN_WIDTH, 240)];
    _headerView.backgroundColor = [UIColor whiteColor];
    return _headerView;
}

- (UIButton *)doneButton {
    if (_doneButton) {
        return _doneButton;
    }
    _doneButton = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 60, 0, 50, 40)];
    [_doneButton setTitle:@"完成" forState:UIControlStateNormal];
    [_doneButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_doneButton addTarget:self action:@selector(finishPick:) forControlEvents:UIControlEventTouchUpInside];

    return _doneButton;
}

- (UIButton *)cancelButton {
    if (_cancelButton) {
        return _cancelButton;
    }
    _cancelButton = [[UIButton alloc] initWithFrame:CGRectMake(10, 0, 50, 40)];
    [_cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    [_cancelButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_cancelButton addTarget:self action:@selector(cancelPick:) forControlEvents:UIControlEventTouchUpInside];
    return _cancelButton;
}

-(UILabel *)currentValueLabel {
    if (_currentValueLabel) {
        return _currentValueLabel;
    }
    _currentValueLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.cancelButton.frame) + 5, 0, CGRectGetMinX(self.doneButton.frame) - CGRectGetMaxX(self.cancelButton.frame) - 10, 40)];
    _currentValueLabel.textColor = [UIColor lightGrayColor];
    _currentValueLabel.textAlignment = NSTextAlignmentCenter;
    _currentValueLabel.font = [UIFont systemFontOfSize:15];
    return _currentValueLabel;
}


- (void)setSelectedDate:(NSDate *)selectedDate {
    if (!selectedDate) {
        selectedDate = [[NSDate alloc] init];
    }
        _selectedDate = selectedDate;
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    switch (self.datePicker.datePickerMode) {
        case UIDatePickerModeDate:
            formatter.dateFormat = @"yyyy.MM.dd";
            break;
        case UIDatePickerModeTime:
            formatter.dateFormat = @"HH:mm";
            break;
        case UIDatePickerModeCountDownTimer:
            formatter.dateFormat = @"HH小时mm分钟";
            break;
        default:
            formatter.dateFormat = @"yyyy.MM.dd HH:mm";
            break;
    }
     //大写HH为24小时制
    self.currentValueLabel.text = [formatter stringFromDate:_selectedDate];
}

- (void)setSelectedIndex:(NSInteger)selectedIndex {
    if (selectedIndex < 0) {
        selectedIndex = 0;
    }
    _selectedIndex = selectedIndex;
    
    if (_selectedIndex < self.dataArray.count ) {
        self.currentValueLabel.text = [NSString stringWithFormat:@"%@", self.dataArray[_selectedIndex]];
    }
    
    
}










@end
